package com.wehealth;


import java.util.Calendar;
import java.util.List;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_PlanDay;
import com.wehealth.dm.DM_PlanDay;
import com.wehealth.parse.ParseJson;
import com.wehealth.util.DoTask;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class Plan_Day_Old extends Fragment {
	
	private ListView lv_planDay;
	
	private List<DM_PlanDay> plan_list;
	
	ProgressDialog pd = null;
	
	MainActivity activity;
	
	int weekday;
	
	private String[] playday_select ={"修改提醒时间","修改食谱","标记完成","取消"};
	private PlayDayDialog playdayDialog;
	private static final int CHANGE_TIME = 0;
	private static final int CHANGE_RECIPE = 1;
	private static final int TAG_COMPLE = 2;
	private static final int  CANCLE = 3; 
	private DM_PlanDay mOnclickItem;
	private Adapter_PlanDay adapter;
	
	
	public  Plan_Day_Old()
	{
		weekday = 1; //默认星期一
				
		Log.i("init:", "Plan_Day"); 
	}
	
	
	public  Plan_Day_Old(int iWeek)
	{
		weekday = iWeek;
		
		Log.i("weekday:",  Integer.toString(weekday)); 
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.plan_day, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		
		String strWeekday = "";
		
		switch(weekday)
		{
			case 1: strWeekday = "星期一";
				break;
				
			case 2: strWeekday = "星期二";
			break;
			
			case 3: strWeekday = "星期三";
			break;
			
			case 4: strWeekday = "星期四";
			break;
			
			case 5: strWeekday = "星期五";
			break;
			
			case 6: strWeekday = "星期六";
			break;
			
			case 7: strWeekday = "星期日";
			break;
		}
	
	   

	    activity = (MainActivity)getActivity();
	    MobclickAgent.openActivityDurationTrack(false);
	    TextView title = (TextView)activity.findViewById(R.id.title_PlanDay);
		
	    title.setText(strWeekday);
	    
		
		
		lv_planDay = (ListView)activity.findViewById(R.id.lv_plan_day);
		
		lv_planDay.setOnItemClickListener(new OnItemClickListener() {
			@Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int index,
                    long arg3) {
				    mOnclickItem = plan_list.get(index);
					openSelectDialog();
			}
		});
		
		//请数据列表
		GetListData();

		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) activity.findViewById(R.id.bBack_PlanDay);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
				    activity.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		
	}
	
	
	

	/**
	 * 渲染界面,显示数据
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			//取消加载框
			pd.dismiss();
			//获取请求返回的值
			Bundle bundle = paramMessage.getData();
			String msginfo = bundle.getString("msg");
			if (msginfo.equals("1")) {
				//程序请求失败
				Toast.makeText(activity, "网络连接失败,稍后重试", Toast.LENGTH_LONG).show();
				return;
			}else {
				plan_list = ParseJson.GetPlanList(msginfo);
				
				
				 adapter =	new Adapter_PlanDay(activity, plan_list);
				lv_planDay.setAdapter(adapter);
			}
		}
	};
	/**
	 * 获取商家信息
	 */
	public void GetListData() {
		//构建请求地址
		String getShopListUrl = com.wehealth.util.GetUrl.Plan_GetDay(1, 1, weekday);
		//可能要换种方式进行读取
		DoTask getDrListTask = new DoTask(activity, handler);
		pd = ProgressDialog.show(activity, "请稍候", "正在获取数据...",false);
		getDrListTask.execute(getShopListUrl);	
	}
	

	private void openSelectDialog(){
		MainActivity context = (MainActivity)getActivity();
		
		PlaydayListOnItemClickListener  playdatOnItemClickListener = new PlaydayListOnItemClickListener();
		
		
		
		playdayDialog = new PlayDayDialog(context,R.style.selectDepartDialog,
				playdatOnItemClickListener,playday_select);
		String title = context.getResources().getString(R.string.playday_dialog_title);
		playdayDialog.setTitle(title);
		playdayDialog.show();		
	}
	
	class PlaydayListOnItemClickListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int index,
				long pos2) {
			// TODO Auto-generated method stub
			switch (index) {
			case CHANGE_TIME:
			    openSetTimeDialog();
				break;
			case CHANGE_RECIPE:
				
				break;
			case TAG_COMPLE:
				tagItemComple();
				playdayDialog.dismiss();
				break;
			case CANCLE:
				playdayDialog.dismiss();
				break;

			default:
				break;
			}

		}	
	}
	
	
	private void openSetTimeDialog(){
	    Context context=activity;
	    String title = getString(R.string.change_time);
	    
	    AlertDialog.Builder builder = new AlertDialog.Builder(context);  
	    View view = View.inflate(context, R.layout.set_time_dialog, null);
	    final TimePicker timePicker =
	            (android.widget.TimePicker) view.findViewById(R.id.time_picker); 
	    builder.setView(view);  
	    Calendar cal = Calendar.getInstance(); 
	    cal.setTimeInMillis(System.currentTimeMillis());  
	    
	    timePicker.setIs24HourView(true);  
	    timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));  
	    timePicker.setCurrentMinute(Calendar.MINUTE); 
	    builder.setTitle(title);  
	    builder.setPositiveButton("OK",new OnClickListener() {
            
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                StringBuffer sb = new StringBuffer();
                sb.append(timePicker.getCurrentHour()) 
                .append(":").append(timePicker.getCurrentMinute());
                String text = sb.toString();
                mOnclickItem.setTime(text);
                adapter.notifyDataSetChanged();
                playdayDialog.cancel();
            }
        });
	    

	    builder.show();  
	    
	}
	
	
    private void resetTime() {
        AlertDialog.Builder mDialog = new Builder(activity);

        String title = getString(R.string.change_time);
        String ok = getString(R.string.ok);
        mDialog.setTitle(title);
        mDialog.setIcon(android.R.drawable.ic_dialog_info);

        final EditText et = new EditText(activity);
        final String defaul_time = mOnclickItem.getTime();
        et.setHint(defaul_time);
        mDialog.setView(et);
        mDialog.setPositiveButton(ok, new OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                String fingerName = et.getText().toString().trim();
                if(fingerName==null){
                	fingerName=defaul_time;
                }
                mOnclickItem.setTime(fingerName);
                adapter.notifyDataSetChanged();
            }
        });
        mDialog.show();
    }
    
    
    private void tagItemComple(){
    	int state = mOnclickItem.getState();
    	if(state==0){
    		mOnclickItem.setState(1);
    	}else{
    		mOnclickItem.setState(0);
    	}
    	 adapter.notifyDataSetChanged();
    }
	
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Plan_Day"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Plan_Day"); 
    }
}
